package com.ffapp.demo.user;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.ffapp.demo.basis.BasisApp;
import com.ffapp.demo.basis.Constants;
import com.ffapp.demo.bean.BasisBean;
import com.ffapp.demo.bean.ContactListBean;
import com.ffapp.demo.bean.HomeGrideListBean;
import com.ffapp.demo.bean.LoginBean;
import com.ffapp.demo.bean.UserBaseInfoUpdateCache;
import com.ffapp.demo.bean.UserInfoBean;
import com.ffapp.demo.greendao.GreenDaoUtils;
import com.ffapp.demo.login.LoginActivity;
import com.ffapp.demo.R;
import com.ffapp.demo.home.HomeBaseActivity;
import com.ffapp.demo.other.PdfScanActivity;
import com.ffapp.demo.setting.AboutUsActivity;
import com.flyco.dialog.listener.OnBtnClickL;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.uuzuche.lib_zxing.activity.CaptureActivity;
import com.uuzuche.lib_zxing.activity.CodeUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import butterknife.BindView;
import butterknife.OnClick;
import my.ActivityTool;
import my.DialogUtils;
import my.IntentUtils;
import my.LogUtil;
import my.MySharedPreferences;
import my.TimeUtils;
import my.http.MyHttpListener;
import my.http.MyHttpUtils;
import my.http.MyParams;


public class UserIndexActivity extends HomeBaseActivity {


    @BindView(R.id.tv_name)
    TextView textName;
    @BindView(R.id.tv_content)
    TextView textContent;
    @BindView(R.id.img_photo)
    ImageView img_photo;
    @BindView(R.id.text_baseinfo_updatetime)
    TextView text_baseinfo_updatetime;

    @BindView(R.id.text_signin_couont)
    TextView text_signin_couont;
    @BindView(R.id.view_mysignin_zone)
    View view_mysignin_zone;

    @Override
    public void initViews() {
        setContentView(R.layout.user_index_activity);
        super.initViews();
        setTitleBg(R.color.transparent);
        ((TextView) findViewById(R.id.base_title_text)).setTextColor(getResources().getColor(R.color.white));
        setTitle("我的");
        setTitleRightButton(R.drawable.personal_icon_qr, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                qrcodeScan();
            }
        });
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        checkUpdata();
        MySharedPreferences mSp = new MySharedPreferences(this);
        textName.setText("");
        textContent.setText("" + mSp.getUser());
        setUpdateBaseInfoTimeView();
        EventBus.getDefault().register(this);
        if(LoginBean.isLogin() && LoginBean.getInstance().getUserInfo() != null){
            setUserView(LoginBean.getInstance().getUserInfo());
        }
    }


    void getUserInfo() {
        MyParams params = new MyParams();
//        showProgress();
        params.put("projectNo",Constants.PROJECT_NO);
        params.put("appType","APP");
//        params.put(MyParams.PARAMS_LOG,"false");
        MyHttpUtils.post(Constants.URL_USER_REFRESH_LOGININFO, params, new MyHttpListener() {
                    @Override
                    public void onSuccess(int httpWhat, Object result) {
                        if (isFinishing()) return;
                        UserInfoBean bean = (UserInfoBean) result;
                        LoginBean loginBean = LoginBean.getInstance();
                        if(loginBean == null)return;
                        loginBean.setUserInfo(bean);
                        loginBean.save();
                        setUserView(bean);
                    }

                    @Override
                    public void onFailure(int httpWhat, Object result) {
//                        super.onFailure(httpWhat, result);
                    }

                    @Override
                    public void onFinish(int httpWhat) {
                        if (isFinishing()) return;
                        hideLoading();
                    }
                },
                0, UserInfoBean.class);
    }


    @Override
    protected void onResume() {
        super.onResume();
        getUserInfo();
        getMySigninNum();
        checkRightAndShow();
//        getImmersionBar().statusBarDarkFont(true,0.5f);
//        getImmersionBar().statusBarDarkFont(true).init();
    }

    @Override
    public void onDoubleClick() {
        super.onDoubleClick();
        if(isFinishing())return;
        getUserInfo();
        getMySigninNum();
        checkRightAndShow();
    }

    void getMySigninNum() {
        MyParams params = new MyParams();
//        showProgress();
        MyHttpUtils.post(Constants.URL_SIGNIN_NEED_SIGN_COUNT, params, new MyHttpListener() {
                    @Override
                    public void onSuccess(int httpWhat, Object result) {
                        if (isFinishing()) return;
                        BasisBean bean = (BasisBean) result;
                        if(TextUtils.isEmpty(bean.getResultData())){
                            text_signin_couont.setVisibility(View.VISIBLE);
                        }else {
                            int count = 0;
                            try {
                                count = Integer.valueOf(bean.getResultData());
                            }catch (Exception e){
                                e.printStackTrace();
                            }
                            if(count > 99){
                                count = 99;
                            }
                            text_signin_couont.setVisibility(count == 0 ? View.GONE:View.VISIBLE);
                            text_signin_couont.setText(count+"");
                        }
                    }

                    @Override
                    public void onFailure(int httpWhat, Object result) {
//                        super.onFailure(httpWhat, result);
                        text_signin_couont.setVisibility(View.GONE);
                    }

                    @Override
                    public void onFinish(int httpWhat) {
                    }
                },
                0, BasisBean.class);
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    private void setUserView(UserInfoBean userInfoDetailBean) {
        textName.setText(userInfoDetailBean.getName());
        textContent.setText("职位：" + userInfoDetailBean.getPost());
        if (!TextUtils.isEmpty(userInfoDetailBean.getAvatar())) {
            BasisApp.loadImg(mContext,userInfoDetailBean.getAvatar(), img_photo,R.drawable.user_sign_icon_photo);
        }
    }

    private void setUpdateBaseInfoTimeView(){
        UserBaseInfoUpdateCache updateCache = UserBaseInfoUpdateCache.getFromCache();
        if(updateCache == null){
            text_baseinfo_updatetime.setText("");
        }else {
            text_baseinfo_updatetime.setText(updateCache.getLatestUpdateTime());
        }
    }


    @OnClick(R.id.view_logout)
    void logout() {
//        DialogUtils.DialogTwo(mContext, "", "退出当前账号？", "立即退出", "取消", new OnBtnClickL() {
//            @Override
//            public void onBtnClick() {
//                LoginActivity.toLoginAllClear(mContext);
//            }
//        },null);

        new QMUIDialog.MessageDialogBuilder(mContext).setMessage("退出当前账号？").addAction("取消", new QMUIDialogAction.ActionListener() {
            @Override
            public void onClick(QMUIDialog dialog, int index) {
                dialog.dismiss();
            }
        }).addAction(0, "立即退出", QMUIDialogAction.ACTION_PROP_NEGATIVE, new QMUIDialogAction.ActionListener() {
            @Override
            public void onClick(QMUIDialog dialog, int index) {
                LoginActivity.toLoginAllClear(mContext);
            }
        }).create().show();
    }


    @OnClick(R.id.view_modifypwd)
    void modifypwd() {
        ActivityTool.skipActivity(mContext, ModifyPwdActivity.class);
    }


    public void checkUpdata() {


//        MyParams params = new MyParams();
//        params.put("id", "MHJYZHCZ");
//        params.put("version", SystemParamsUtils.getAPPVersonCode(mContext));
//        MyHttpUtils.post(Constants.URL_UPDATE, params, new MyHttpListener() {
//            @Override
//            public void onSuccess(int httpWhat, Object result) {
//                UpdateBean updateBean = (UpdateBean) result;
//               if(updateBean.isNeedUpdate(mContext)){
//                   img_update_point.setVisibility(View.VISIBLE);
//               }else{
//                   img_update_point.setVisibility(View.GONE);
//               }
//            }
//
//            @Override
//            public void onFailure(int httpWhat, Object result) {
////                super.onFailure(httpWhat, result);
//                img_update_point.setVisibility(View.GONE);
//            }
//
//            @Override
//            public void onFinish(int httpWhat) {
//                        dismissProgress();
//            }
//
//        }, 0, UpdateBean.class);

    }

    private static final int REQUEST_QRCODE = 11;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (REQUEST_QRCODE == requestCode) {
            if (null != data) {
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    return;
                }
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                    String result = bundle.getString(CodeUtils.RESULT_STRING);
//                    showToast("解析结果=="+result);
                    if (result.startsWith("xfbook:")) {//预约
//                        String id = result.substring(result.indexOf("xfbook:") + 7);
//                        Bundle extras = new Bundle();
//                        extras.putString("id", id);
//                        ActivityTool.skipActivity(mContext, VisitConfirmActivity.class, extras);
                    }
//                    else if(result.startsWith("http://app.ff-cloud.net/download/detail/id/bd16ead2-cc45-5cf0-6ae3-355e156ff75e.html")) {
                    else if (result.startsWith("http")) {
                        IntentUtils.ViewUrl(mContext, result);
                    } else {
                        DialogUtils.DialogOkMsg(mContext, "二维码内容与本应用无关\n" + result);
                    }


                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                    showToast("解析二维码失败");
                }
            }
        }
    }

//    @OnClick(R.id.view_qrcode_scan)
    void qrcodeScan() {
        Intent intent = new Intent(mContext, CaptureActivity.class);
        startActivityForResult(intent, REQUEST_QRCODE);
    }



    @OnClick(R.id.view_help)
    void help() {
        PdfScanActivity.toPdfScanActivity(mContext, "厦门消防APP使用手册_V2.0_20210107.pdf", "用户手册");
    }

    @OnClick(R.id.view_aboutus)
    void aboutUs() {
        ActivityTool.skipActivity(mContext, AboutUsActivity.class);
    }

    @OnClick(R.id.view_map_offlinedata_update)
    void onMapofflineClick() {
        startActivity(new Intent(mContext,
                com.amap.api.maps.offlinemap.OfflineMapActivity.class));
//        test();
    }

    @OnClick(R.id.view_basedata_update)
    void onBasedataUpdateClick() {

        checkCacheUpdate();
//        test();
    }

    UserBaseInfoUpdateCache cacheOld;
    void checkCacheUpdate(){
        cacheOld = UserBaseInfoUpdateCache.getFromCache();
        if(cacheOld != null && (!ContactListBean.isCacheExist() || GreenDaoUtils.getListBeanCount()== 0)){
            cacheOld = new UserBaseInfoUpdateCache();
            cacheOld.save();
        }
//        Calendar calendar = Calendar.getInstance();
//        calendar.add(Calendar.HOUR_OF_DAY,-8);
//        cache.setLastCacheUpdateTime(calendar.getTimeInMillis());
//        cache = new UserBaseInfoUpdateCache();
//        cache.setUnitTime(new Date().getTime());
            MyParams params = new MyParams();
//            params.put("lastCacheUpdateTime",TimeUtils.getTimeLongToStrByFormat(cache.getLastCacheUpdateTime(),"yyyy-MM-dd HH:mm:ss"));
        params.put("unitTime",cacheOld == null ?"":TimeUtils.getTimeLongToStrByFormat(cacheOld.getUnitTime(),"yyyy-MM-dd HH:mm:ss"));
        params.put("stationTime",cacheOld == null ?"":TimeUtils.getTimeLongToStrByFormat(cacheOld.getStationTime(),"yyyy-MM-dd HH:mm:ss"));
        params.put("buildingTime",cacheOld == null ?"":TimeUtils.getTimeLongToStrByFormat(cacheOld.getBuildingTime(),"yyyy-MM-dd HH:mm:ss"));
        params.put("trainTime",cacheOld == null ?"":TimeUtils.getTimeLongToStrByFormat(cacheOld.getTrainTime(),"yyyy-MM-dd HH:mm:ss"));
        params.put("userTime",cacheOld == null ?"":TimeUtils.getTimeLongToStrByFormat(ContactListBean.getLastCacheTime(),"yyyy-MM-dd HH:mm:ss"));
        params.put("riskTime",cacheOld == null ?"":TimeUtils.getTimeLongToStrByFormat(cacheOld.getRiskTime(),"yyyy-MM-dd HH:mm:ss"));
        params.put("waterTime",cacheOld == null ?"":TimeUtils.getTimeLongToStrByFormat(cacheOld.getWaterTime(),"yyyy-MM-dd HH:mm:ss"));
//        params.put("type",cache == null ?"":TimeUtils.getTimeLongToStrByFormat(cache.getLastCacheUpdateTime(),"yyyy-MM-dd HH:mm:ss"));
//        params.put("userCacheTime","2020-01-01 12:00:00");
        showLoading();
            MyHttpUtils.post(Constants. URL_USER_BASEINFO_ISUPDATECACHE, params, new MyHttpListener() {
                        @Override
                        public void onSuccess(int httpWhat, Object result) {
                            UserBaseInfoUpdateCache beanNew = (UserBaseInfoUpdateCache) result;
                            beanNew.setAllNeedUpdate(true);
                            beanNew.sychoTimeFromOld(cacheOld);
//                            beanNew.setForceUpdate(true);
//                            beanNew.setUserCount(9999);
//                            beanNew.setOneTypeNeedUpdate(GreenDaoUtils.TYPE_USER);

//                            LogUtil.i("beanNew--->"+JSON.toJSONString(beanNew));
                            if(beanNew.isNeedUpdateUser()){
                                getContactList();
                            }
                            if(beanNew.isNeedUpdate()){
                                DialogUtils.DialogTwo(mContext, "基础数据更新", "是否立即更新？", "确定", "取消", new OnBtnClickL() {
                                    @Override
                                    public void onBtnClick() {
//                                        UserIndexActivity.updateBaseInfoData(mContext,beanNew,true);
                                        UpdateBaseInfoDialog.toBaseInfoUpdateDialog(mContext,beanNew);

                                    }
                                },null);
                            }else {
                                DialogUtils.DialogOkMsg(mContext,"已是最新数据，无需更新");
                            }
                        }

                        @Override
                        public void onFailure(int httpWhat, Object result) {
                        super.onFailure(httpWhat, result);
                            LogUtil.i("检测缓存是否有更新->onFailure");
                        }

                        @Override
                        public void onFinish(int httpWhat) {
                            dismissProgress();
                        }
                    },
                    0, UserBaseInfoUpdateCache.class);
    }




    @Subscribe
    public  void onBaseInfoUpdate(GreenDaoUtils.EventDateChange eventDateChange){
        if(isFinishing())return;
        setUpdateBaseInfoTimeView();
    }

    private void getContactList() {
        MyParams params = new MyParams();
//        showProgress();
        params.put("showAll", "false");
        MyHttpUtils.post(Constants.URL_USER_CONTACT, params, new MyHttpListener() {
                    @Override
                    public void onSuccess(int httpWhat, Object result) {
                        ContactListBean mListBean = (ContactListBean) result;
                        mListBean.save();
                    }

                    @Override
                    public void onFailure(int httpWhat, Object result) {
//                        super.onFailure(httpWhat, result);
                    }

                    @Override
                    public void onFinish(int httpWhat) {
                    }
                },
                0, ContactListBean.class);

    }



    void checkRightAndShow(){
        HomeGrideListBean homeGrideListBean = (HomeGrideListBean) new HomeGrideListBean().getObjFromCache();
        if(homeGrideListBean == null)return;
        if(homeGrideListBean.isRightByName("点名签到")){
            view_mysignin_zone.setVisibility(View.VISIBLE);
        }else {
            view_mysignin_zone.setVisibility(View.GONE);
        }
    }
}
